package com.zhhtech.zhh.ui.utils

import android.app.Activity
import android.content.ClipData
import android.content.ClipboardManager
import android.content.Context
import android.content.Intent
import android.content.pm.PackageManager
import android.content.res.Resources
import android.graphics.Bitmap
import android.graphics.BitmapFactory
import android.net.ConnectivityManager
import android.net.Uri
import android.os.Build
import android.os.Environment
import android.provider.MediaStore
import android.text.TextUtils
import android.util.TypedValue
import android.view.View
import android.view.inputmethod.InputMethodManager
import android.widget.EditText
import android.widget.TextView
import android.widget.Toast
import java.io.*

/**
 * Created by Administrator on 2017/3/21 0021.
 */
object Utils {
    // 两次点击按钮之间的点击间隔不能少于1000毫秒
    private const val MIN_CLICK_DELAY_TIME = 300
    private var lastClickTime: Long = 0
    private const val INDEX_NOT_FOUND = -1

    /**
     * 限制重复点击
     *
     * @return true，没有重复点击；false，minClickDelayTime 内连续点击两次
     */
    @JvmStatic
    fun notRepeatClick() = notRepeatClick(MIN_CLICK_DELAY_TIME)

    /**
     * 限制重复点击
     *
     * @return true，没有重复点击；false，300ms 内连续点击两次
     */
    @JvmStatic
    fun notRepeatClick(minClickDelayTime: Int): Boolean {
        val curClickTime = System.currentTimeMillis()
        if (curClickTime - lastClickTime >= minClickDelayTime) {
            lastClickTime = curClickTime
            return true
        }
        lastClickTime = curClickTime
        return false
    }

    @JvmStatic
    fun setVisibility(visibility: Int, vararg view: View) {
        for (item in view) {
            item.visibility = visibility
        }
    }

    @JvmStatic
    fun isEmpty(str: String?): Boolean {
        return str == null || str.isEmpty()
    }

    @JvmStatic
    fun defaultIsEmpty(str: String?, defaultStr: String): String {
        return (if (isEmpty(str)) defaultStr else str)!!
    }

    @JvmStatic
    fun isTextViewValueEmpty(textView: View): Boolean {
        return isEmpty(getTextViewValue(textView))
    }

    @JvmStatic
    fun getTextViewValue(textView: View): String {
        return getTextViewValue(textView as TextView)
    }

    @JvmStatic
    fun getTextViewValue(textView: TextView): String {
        return textView.text.toString().trim { it <= ' ' }
    }

    /**
     * <p>Strips any of a set of characters from the end of a String.</p>
     *
     * <p>A {@code null} input String returns {@code null}.
     * An empty string ("") input returns the empty string.</p>
     *
     * <p>If the stripChars String is {@code null}, whitespace is
     * stripped as defined by {@link Character#isWhitespace(char)}.</p>
     *
     * <pre>
     * StringUtils.stripEnd(null, *)          = null
     * StringUtils.stripEnd("", *)            = ""
     * StringUtils.stripEnd("abc", "")        = "abc"
     * StringUtils.stripEnd("abc", null)      = "abc"
     * StringUtils.stripEnd("  abc", null)    = "  abc"
     * StringUtils.stripEnd("abc  ", null)    = "abc"
     * StringUtils.stripEnd(" abc ", null)    = " abc"
     * StringUtils.stripEnd("  abcyx", "xyz") = "  abc"
     * StringUtils.stripEnd("120.00", ".0")   = "12"
     * </pre>
     *
     * @param str  the String to remove characters from, may be null
     * @param stripChars  the set of characters to remove, null treated as whitespace
     * @return the stripped String, {@code null} if null String input
     */
    @JvmStatic
    fun stripEnd(str: String, stripChars: String?): String? {
        var end: Int = length(str)
        if (end == 0) {
            return str
        }
        if (stripChars == null) {
            while (end != 0 && Character.isWhitespace(str[end - 1])) {
                end--
            }
        } else if (stripChars.isEmpty()) {
            return str
        } else {
            while (end != 0 && stripChars.indexOf(str[end - 1]) != INDEX_NOT_FOUND) {
                end--
            }
        }
        return str.substring(0, end)
    }

    @JvmStatic
    fun length(cs: CharSequence?): Int {
        return cs?.length ?: 0
    }

    @JvmStatic
    fun callPhoneUrl(context: Context, url: String?) {
        val intent = Intent(Intent.ACTION_DIAL, Uri.parse(url))
        intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK)
        context.startActivity(intent)
    }

    @JvmStatic
    fun callPhone(context: Context, phone: String) {
        val intent = Intent(Intent.ACTION_DIAL, Uri.parse("tel:$phone"))
        intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK)
        context.startActivity(intent)
    }

    @JvmStatic
    fun setTextNotEmpty(view: TextView, value: Any?, def: String?) {
        view.text = if (value == null || value is String && isEmpty(
                value as String?
            )
        ) def else value.toString() + ""
    }

    @JvmStatic
    fun setTextNotEmpty(view: TextView, value: Any?) {
        setTextNotEmpty(view, value, "")
    }

    @JvmStatic
    fun replaceStar(text: String, startIndex: Int, endIndex: Int): String {
        if (!TextUtils.isEmpty(text) && startIndex <= endIndex) {
            val chars = text.toCharArray()
            val start = Math.max(startIndex, 0)
            val size = Math.min(endIndex, text.length - 1)
            for (i in start..size) {
                chars[i] = '*'
            }
            return String(chars)
        }
        return text
    }

    @JvmStatic
    fun getAppRootPath(context: Context): File {
        return if (sdCardIsAvailable()) {
            Environment.getExternalStorageDirectory()
        } else {
            context.filesDir
        }
    }

    @JvmStatic
    fun setDefaultStatusBarFont(activity: Activity?) {
        setDefaultStatusBarFont(activity, true)
    }

    @JvmStatic
    fun setDefaultStatusBarFont(activity: Activity?, darkFont: Boolean) {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            com.yanzhenjie.sofia.Utils.setStatusBarDarkFont(activity, darkFont)
        }
    }

    @JvmStatic
    fun invasionStatusBar(activity: Activity?) {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            com.yanzhenjie.sofia.Utils.invasionStatusBar(activity)
        }
    }

    @JvmStatic
    fun sdCardIsAvailable(): Boolean {
        return if (Environment.getExternalStorageState() == Environment.MEDIA_MOUNTED) {
            Environment.getExternalStorageDirectory().canWrite()
        } else false
    }

    @JvmStatic
    fun saveImageToGallery(context: Context, bmp: Bitmap): Boolean {
        try {
            // 首先保存图片
            val storePath = Environment.getExternalStorageDirectory()
                .absolutePath + File.separator + "salon_m"
            val appDir = File(storePath)
            if (!appDir.exists()) {
                appDir.mkdir()
            }
            val fileName = System.currentTimeMillis().toString() + ".jpg"
            val file = File(appDir, fileName)
            val fos = FileOutputStream(file)
            //通过io流的方式来压缩保存图片
            val isSuccess = bmp.compress(Bitmap.CompressFormat.JPEG, 60, fos)
            fos.flush()
            fos.close()
            //把文件插入到系统图库
            MediaStore.Images.Media.insertImage(
                context.contentResolver,
                file.absolutePath,
                fileName,
                null
            )
            //保存图片后发送广播通知更新数据库
            val uri = Uri.fromFile(file)
            context.sendBroadcast(Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE, uri))
            return isSuccess
        } catch (e: IOException) {
            e.printStackTrace()
        }
        return false
    }

    /**
     * 检查网络是否可用
     *
     * @param context
     * @return
     */
    @JvmStatic
    fun isNetworkAvailable(context: Context): Boolean {
        val manager = context.applicationContext.getSystemService(Context.CONNECTIVITY_SERVICE) as ConnectivityManager
        val networkinfo = manager.activeNetworkInfo
        return !(networkinfo == null || !networkinfo.isAvailable)
    }

    @JvmStatic
    fun getBitmapOptions(filePath: String?): BitmapFactory.Options {
        val options = BitmapFactory.Options()
        options.inJustDecodeBounds = true
        BitmapFactory.decodeFile(filePath, options)
        return options
    }

    @JvmStatic
    fun duration(durationMs: Long): String {
        val duration = durationMs / 1000
        val h = duration / 3600
        val m = (duration - h * 3600) / 60
        val s = duration - (h * 3600 + m * 60)
        val durationValue: String = if (h == 0L) {
            asTwoDigit(m) + ":" + asTwoDigit(
                s
            )
        } else {
            asTwoDigit(h) + ":" + asTwoDigit(
                m
            ) + ":" + asTwoDigit(s)
        }
        return durationValue
    }

    /**
     * 时间格式化
     */
    @JvmStatic
    fun formattedTime(second: Long): String {
        val hs: String
        val ms: String
        val ss: String
        val formatTime: String
        val h: Long = second / 3600
        val m: Long = second % 3600 / 60
        val s: Long = second % 3600 % 60
        hs = if (h < 10) {
            "0$h"
        } else {
            "" + h
        }
        ms = if (m < 10) {
            "0$m"
        } else {
            "" + m
        }
        ss = if (s < 10) {
            "0$s"
        } else {
            "" + s
        }
        formatTime = if (h > 0) {
            "$hs:$ms:$ss"
        } else {
            "$ms:$ss"
        }
        return formatTime
    }

    @JvmStatic
    fun asTwoDigit(digit: Long): String {
        var value = ""
        if (digit < 10) {
            value = "0"
        }
        value += digit.toString()
        return value
    }

    /**
     * 复制文本到剪切板
     *
     * @param context
     * @param text
     */
    @JvmStatic
    fun setClipText(context: Context?, text: String?) {
        if (context == null) return
        val myClipboard =
            context.getSystemService(Context.CLIPBOARD_SERVICE) as ClipboardManager?
        myClipboard?.setPrimaryClip(ClipData.newPlainText(null, text))
    }

    /**
     * 根据比例转化实际数值为相对值
     *
     * @param gear 档位
     * @param max  最大值
     * @param curr 当前值
     * @return 相对值
     */
    @JvmStatic
    fun filtNumber(gear: Int, max: Int, curr: Int): Int {
        return curr / (max / gear)
    }

    @JvmStatic
    fun getMeatIcon(
        context: Context,
        clz: Class<*>,
        key: String?,
    ): Int {
        try {
            val info = context.packageManager
                .getApplicationInfo(context.packageName, PackageManager.GET_META_DATA)
            val welcomePath = info.metaData.getString(key)
            val fields = clz.fields
            for (field in fields) {
                val substring = welcomePath!!.substring(
                    welcomePath.lastIndexOf("/") + 1,
                    welcomePath.lastIndexOf(".")
                )
                if (field.name == substring) {
                    return field[null] as Int
                }
            }
        } catch (e: Exception) {
            e.printStackTrace()
        }
        return 0
    }

    @JvmStatic
    fun getMeatDataString(context: Context, key: String?): String? {
        try {
            val info = context.packageManager
                .getApplicationInfo(context.packageName, PackageManager.GET_META_DATA)
            return info.metaData.getString(key)
        } catch (e: Exception) {
            e.printStackTrace()
        }
        return ""
    }

    @JvmStatic
    // 将Bitmap转换成InputStream(压缩率quality、100表示不压缩、10表示压缩90%)
    fun Bitmap2InputStream(bm: Bitmap, quality: Int): InputStream {
        val baos = ByteArrayOutputStream()
        bm.compress(Bitmap.CompressFormat.PNG, quality, baos)
        return ByteArrayInputStream(baos.toByteArray())
    }

    @JvmStatic
    // 将Bitmap转换成InputStream
    fun Bitmap2InputStream(bm: Bitmap): InputStream {
        val baos = ByteArrayOutputStream()
        bm.compress(Bitmap.CompressFormat.JPEG, 100, baos)
        return ByteArrayInputStream(baos.toByteArray())
    }

    @JvmStatic
    fun showView(vararg view: View?) {
        if (view != null && view.size > 0) {
            for (viewItem in view) {
                showView(viewItem)
            }
        }
    }

    @JvmStatic
    fun showView(view: View?) {
        if (view != null && view.visibility == View.GONE) {
            view.visibility = View.VISIBLE
        }
    }

    @JvmStatic
    fun hideView(vararg view: View?) {
        if (view != null && view.size > 0) {
            for (viewItem in view) {
                hideView(viewItem)
            }
        }
    }

    @JvmStatic
    fun hideSoftInput(activity: Activity?) {
        try {
            hideSoftInput(activity?.window?.currentFocus)
        } catch (e: Exception) {
            Logger.e(e)
        }
    }

    @JvmStatic
    fun hideSoftInput(view: View?) {
        try {
            if (view == null) return
            val imm =
                view.context.getSystemService(Context.INPUT_METHOD_SERVICE) as InputMethodManager?
            if (imm != null && imm.isActive) {
                imm.hideSoftInputFromWindow(view.windowToken, 0) //强制隐藏键盘
            }
        } catch (e: Exception) {
            Logger.e(e)
        }
    }

    @JvmStatic
    fun showSoftInput(editText: EditText?) {
        if (editText == null) return
        val imm = editText.context
            .getSystemService(Context.INPUT_METHOD_SERVICE) as InputMethodManager
        imm.showSoftInput(editText, 0)
    }

    @JvmStatic
    fun hideView(view: View?) {
        if (view != null && view.visibility == View.VISIBLE) {
            view.visibility = View.GONE
        }
    }// 设置完成后返回到原来的界面


//    fun isNetworkAvailabe(var0: Context): Boolean {
//        var var1: NetworkInfo
//        return if ((var0.getSystemService(Context.CONNECTIVITY_SERVICE) as ConnectivityManager).activeNetworkInfo
//                .also { var1 = it } != null
//        ) var1.isAvailable else false
//    }

    @JvmStatic
    fun toastMessageShort(context: Context, text: String?) {
        Toast.makeText(context, text, Toast.LENGTH_SHORT).show()
    }

    @JvmStatic
    fun toastMessageLong(context: Context, text: String?) {
        Toast.makeText(context, text, Toast.LENGTH_LONG).show()
    }

    @JvmStatic
    fun random8(): Int {
        val random = StringBuilder()
        for (i in 0..7) {
            random.append((Math.random() * 10).toString())
        }
        return random.toString().toInt()
    }

    @JvmStatic
    fun getDouble(d: String?): String {
        var d = d
        if (d == null || d.isEmpty()) return "0"
        d = d.replace("0+?$".toRegex(), "") //去掉后面无用的零
        d = d.replace("[.]$".toRegex(), "") //如小数点后面全是零则去掉小数点
        return d
    }

    @JvmStatic
    fun dp2px(dp: Float): Float {
        return TypedValue.applyDimension(
            TypedValue.COMPLEX_UNIT_DIP,
            dp,
            Resources.getSystem().displayMetrics
        )
    }
}